package com.tledu.web04.controller;

import com.tledu.web04.model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author cyrus
 */
@WebServlet(urlPatterns = {"/register"}, loadOnStartup = 1)
public class RegisterServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
//        this.getServletContext().setAttribute("studentData", new HashMap<String, Student>());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");
        // 获取这些数据进行封装
        Student student = new Student();
        student.setUsername(req.getParameter("username"));
        student.setPassword(req.getParameter("password"));
        student.setNickname(req.getParameter("nickname"));
        student.setAge(Integer.parseInt(req.getParameter("age")));
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            student.setBirthday(simpleDateFormat.parse(req.getParameter("birthday")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 把这个对象存起来
        HashMap<String, Student> studentData = (HashMap<String, Student>) this.getServletContext().getAttribute("studentData");
        // 判断这个key是否存在
        if (studentData.containsKey(student.getUsername())) {
            // 说名这个用户名已经存在了
            // 通过界面进行展示
            req.setAttribute("error","用户名已经存在");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            return;
        }
        // 这个key应该不存在的
        studentData.put(student.getUsername(), student);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
}
